package com.qckj.common.okhttpUtils;

import org.springframework.web.bind.annotation.RequestBody;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.Iterator;
import java.util.Map;

public class OkhttpUtils {

    /**
     * 当前请求方式为okhttp post方式，改方式可供postman调试代码方式，可供菜鸟使用，okhttp也是很高效的，不比http效率差
     * @param url
     * @param bodyParams
     * @return
     */
    /*public static String postApi(String url, Map<String, String> bodyParams){
        String res = "";
        OkHttpClient client = new OkHttpClient().newBuilder().build();
        RequestBody body = setRequestBody(bodyParams);
        Request request = new Request.Builder()
                .url(url)
                .method("POST", body)
                .build();
        try {
            Response response = client.newCall(request).execute();
            InputStream inputStream = response.body().byteStream();
            BufferedReader breader = new BufferedReader(new InputStreamReader(inputStream,"utf-8"));  //请注意这里的编码
            StringBuilder responseString = new StringBuilder();
            String line = "";
            while ((line = breader.readLine()) !=null) {
                responseString.append(line);
            }
            breader.close();
            res =responseString.toString();

            System.out.println(res);
        } catch (IOException e) {
            e.printStackTrace();
        }

        return res;
    }

    private static RequestBody setRequestBody(Map<String, String> params) {
        RequestBody body = null;
        FormBody.Builder formBuilder = new FormBody.Builder();
        if (params != null && params.keySet() != null && params.keySet().size() > 0) {
            String key;
            Iterator<String> iterator = params.keySet().iterator();
            while (iterator.hasNext()) {
                key = iterator.next().toString();
                formBuilder.add(key, params.get(key));
            }
        }
        body = formBuilder.build();

        return body;
    }*/

}
